﻿
using Newtonsoft.Json; 
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Web;
namespace HBase {
    public class Utils {
        private const int BufSize = 4096;
        /// <summary>
        ///     输出200状态
        /// </summary>

        public static string ReadLine(Stream _inputStream) {
            int next_char;
            var data = "";
            int index = 1000;
            while( true ) {
                try {
                    next_char = _inputStream.ReadByte();
                } catch {

                    LoggerCommon.consol("read_request_error:" + data);
                    break;

                }

                if( next_char == '\n' ) {
                    break;
                }
                if( next_char == '\r' ) {
                    continue;
                }
                if( next_char == -1 ) {
                    index--;
                    if( index < 0 ) {
                        break;
                    } else {
                        continue;
                    }

                }
                ;
                data += Convert.ToChar(next_char);
            }
            return data;
        }
        public static void getData(string rawData ,Dictionary<string ,object> rets) {

            var rawParams = rawData.Split('&');
            foreach( var param in rawParams ) {
                var kvPair = param.Split('=');
                var key = kvPair[0];
                var value = HttpUtility.UrlDecode(kvPair[1]);
                rets[key] = value;
            }

        }
        public static Hashtable ParseRequest(Stream _inputStream) {
            Hashtable HttpHeaders = new Hashtable();
            string line;
            while( (line = ReadLine(_inputStream)) != null ) {
                if( line.Equals("") ) {
                    break;
                }
           
                var separator = line.IndexOf(':');
                if( separator == -1 ) {
                    continue;
                }
                var name = line.Substring(0 ,separator);
                var pos = separator + 1;
                while( (pos < line.Length) && (line[pos] == ' ') ) {
                    pos++; //过滤键值对的空格
                }
                var value = line.Substring(pos ,line.Length - pos);
                HttpHeaders[name] = value;

            }

            return HttpHeaders;
        }
        //读取文件
        public static byte[] getByte(int content_len ,Stream _inputStream) {

            var ms = new MemoryStream();

            var buf = new byte[BufSize];
            var to_read = content_len;
            while( to_read > 0 ) {
                var numread = _inputStream.Read(buf ,0 ,Math.Min(BufSize ,to_read));
                if( numread == 0 ) {
                    if( to_read == 0 ) {
                        break;
                    }
                    throw new Exception("client disconnected during post");
                }
                to_read -= numread;
                ms.Write(buf ,0 ,numread);
            }
            ms.Seek(0 ,SeekOrigin.Begin);

            return ms.ToArray();


        }
        public static string PostRequestExec(Hashtable HttpHeaders ,Stream _inputStream) {
            String boundary = null;
            byte[] buf = new byte[0];
            if( HttpHeaders.ContainsKey("Content-Length") ) {
                if( HttpHeaders.ContainsKey("Content-Type") ) {
                    String type = HttpHeaders["Content-Type"].ToString();
                    if( type.IndexOf("multipart/form-data") != -1 ) {
                        var b = type.Split(';')[1];
                        boundary = b.Split('=')[1].Substring(2);
                    }
                }

                //内容的长度
                int content_len = Convert.ToInt32(HttpHeaders["Content-Length"]);
                buf = getByte(content_len ,_inputStream);
            }

            if( boundary == null ) {
                return System.Text.Encoding.UTF8.GetString(buf);
            } else {
                List<String> names = new List<string>();

                ByteArr line = ReadLine(buf ,0);


                while( line.data.IndexOf(boundary) != -1 ) {
                    line = ReadLine(buf ,line.index);

                    if( line == null ) {
                        break;
                    }
                    int begin = line.data.IndexOf("filename") + 10;
                    if( begin == 9 ) {
                        break;
                    }
                    String name = line.data.Substring(begin ,line.data.Length - begin - 1);
                    if( name.IndexOf("@") != -1 ) {
                        names.Add("文件名不能包含@符");
                    }
                    String fullName = getPath(name);
                    names.Add(fullName.Replace('/' ,'@'));
                    line = writeFile(buf ,line.index ,boundary ,FileCache.Path + fullName);


                }
                return JsonConvert.SerializeObject(names);
            }

        }

        private static ByteArr ReadLine(byte[] b ,int begin) {
            List<byte> l = new List<byte>();
            for( int i = begin;i < b.Length - 1;i++ ) {
                if( b[i] == '\r' && b[i + 1] == '\n' ) {
                    return new ByteArr(l ,i);
                } else {
                    l.Add(b[i]);

                }
            }
            l.Add(b[b.Length - 1]);

            return new ByteArr(l ,b.Length - 1);
        }

        static ByteArr writeFile(byte[] inputData ,int index ,String boundary ,String name) {
            ByteArr type = ReadLine(inputData ,index);

            ByteArr line = ReadLine(inputData ,type.index);


            using( FileStream sw = new FileStream(name ,FileMode.OpenOrCreate) ) {

                line = ReadLine(inputData ,line.index);
                int time = 0;
                while( line.data.IndexOf(boundary) == -1 ) {
                    if( time != 0 ) {
                        sw.WriteByte(( byte ) '\r');
                        sw.WriteByte(( byte ) '\n');
                    }
                    sw.Write(line.b ,0 ,line.b.Length);
                    line = ReadLine(inputData ,line.index);

                    time++;

                }
                return line;
            }



        }

        static String getPath(String name) {
            DateTime n = DateTime.Now;
            String p = n.Year + "/" + n.Month;
            String path = FileCache.Path + p;

            if( !Directory.Exists(path) ) {
                Directory.CreateDirectory(path);
            }

            return p + "/" + n.Day + n.Hour + n.Minute + n.Second + name;
        }


    }

    class ByteArr {
        public ByteArr(byte[] b ,int i) {
            this.b = b;
            data = System.Text.Encoding.UTF8.GetString(b);
            index = i + 2;
        }

        public ByteArr(List<byte> b ,int i) : this(b.ToArray() ,i) {

        }
        public byte[] b;
        public String data;
        public int index;
    }
}
